$(document).ready(function(){
	
	$('.hide-reveal').click( function(e) {
		e.preventDefault();
		var targetElement = $(this).attr('data:target');
		$(targetElement).toggle();
	});
	$('.hide-reveal').each( function() {
		$($(this).attr('data:target')).hide();
	});

	$('.hide').click( function(e) {
		e.preventDefault();
		var targetElement = $(this).attr('data:target');
		$(targetElement).hide();
	});
	
	
	
	/*this is all old stuff below here and may not be needed*/
	
	
	$('.itemdata').hide();
	$('.itemcontrol').rowToggle();
	
	$('.addactivity').addActivity();
	$('.addcostcenter').addCostCenter();
	$('.addcost').addCost();
	
	$('#addaddress').showIfChecked('#address_form');
	$('#addcontact').showIfChecked('#contact_form');
	
	$('.addaddress_link').hideMeShow('#address_form');
	$('.addcontact_link').hideMeShow('#contact_form');
	
	$('#newcompany_link').hideMeShow('#addcompany_container');
	$('#addcompany_button').addOptionTo('#companyid', '#company_name', 'company', 'company_name', '#addcompany_container');
	
	//$(".tablesorter").tablesorter(); 
	
	$("a.complete").markAs('complete');
	$("a.notcomplete").markAs('notcomplete');
	$("a.dismiss").markAs('dismiss');
	$("a.recall").markAs('recall');
	
	$('div.wizard').fieldsetTabs();
	
	$(".selectadd").selectAdd();
		
	$('input[type=submit].linkReplace').linkReplace();
	
	$('div#messagearea p').animate({opacity: 1.0}, 5000).fadeOut('slow', function() {
		$(this).remove();
    });
    
	$('ul.theList li.dismiss').timesheetHover();
	
	$('ul.theList li a.delete').click( function(e) {
		e.preventDefault();
		e.stopPropagation();
		
		var timesheetcontainer = $(this).parents('li');
		var timesheetid = timesheetcontainer.attr('id');
		
		console.log(timesheetcontainer);
		
		$.ajax({
			type: "POST",
			url: siteURL + "/jobs/deleteTimesheet/",
			data: { timesheetid: timesheetid },
			success: function(timesheetid) {
				$(timesheetcontainer).remove();
			}
		});
				
	} );
	
	$('.multiupload').MultiFile( { namePattern: '$name$i', max: 2  }); 

	$('input[name=searchterm]').keyup( function (e) {
		var searchTerm = $(this).val();

		if( searchTerm.length >= 3 ) {
			if ( !$('div#searchresults').length ) $('#wrap').append('<div id="searchresults"></div>');
			
			$.post( siteURL + '/epicentr/quickSearch',
				{searchterm: searchTerm },
				function (searchResults) {
					$('div#searchresults').children().remove();
					
					if (searchResults != 'false') {
						
						if (searchResults['jobs'].length) {
							
							$('div#searchresults').append('<h3 class="title jobs">Jobs</h3><table class="results"></table>');
							
							$.each(searchResults['jobs'], function (i, item) {
								var rowclass = "";
								
								if ( (i % 2) == 1) rowclass = "alt";
								
								var job_title = this['job_title'];
								if (job_title == 'undefined') job_title = '';
								
								var job_number = this['job_number'];
								if (job_number == 'undefined') job_number = '';
								
								var account_code = this['account_code'];
								if (typeof(account_code) == 'undefined') account_code = '';
								
								$('div#searchresults h3.title.jobs + table').append('<tr class="'+rowclass+'"> <td><a href="'+siteURL+'/jobs/view/'+this['jobid']+'">'+job_title+'</a><small>'+job_number+'</small></td> <td>for <a href="'+siteURL+'/companies/view/'+this['companyid']+'">'+this['company_name']+'</a><small>'+account_code+'</small></td> </tr>');
							});
						
						}
						
						if (searchResults['clients'].length) {
						
							$('div#searchresults').append('<h3 class="title clients">Clients</h3><table class="results"></table>');
						
							var account_code = this['account_code'];
							if (typeof(account_code) == 'undefined') account_code = '';
						
							$.each(searchResults['clients'], function (i, item) {
								var rowclass = "";
								
								if ( (i % 2) == 1) rowclass = "alt";
								
								$('div#searchresults h3.title.clients + table').append('<tr class="'+rowclass+'"><td><a href="'+siteURL+'/companies/view/'+this['companyid']+'">'+this['company_name']+'</a><small>'+account_code+'</small></td> </tr>');
							});
							
						}
						
						if (searchResults['prospects'].length) {
						
							$('div#searchresults').append('<h3 class="title prospects">Prospects</h3><table class="results"></table>');
						
							var account_code = this['account_code'];
							if (typeof(account_code) == 'undefined') account_code = '';
						
							$.each(searchResults['prospects'], function (i, item) {
								var rowclass = "";
								
								if ( (i % 2) == 1) rowclass = "alt";
								
								$('div#searchresults h3.title.prospects + table').append('<tr class="'+rowclass+'"><td><a href="'+siteURL+'/companies/view/'+this['companyid']+'">'+this['company_name']+'</a><small>'+account_code+'</small></td> </tr>');
							});
							
						}
						
						if (searchResults['suppliers'].length) {
						
							$('div#searchresults').append('<h3 class="title suppliers">Suppliers</h3><table class="results"></table>');
						
							$.each(searchResults['suppliers'], function (i, item) {
								var rowclass = "";
								
								if ( (i % 2) == 1) rowclass = "alt";
								
								$('div#searchresults h3.title.suppliers + table').append('<tr class="'+rowclass+'"><td><a href="'+siteURL+'/companies/view/'+this['companyid']+'">'+this['company_name']+'</a><small>'+this['account_code']+'</small></td> </tr>');
							});
							
						}
					}
					
					if ( !$('div#searchresults').children().length ) $('div#searchresults').append('<p><em>No matching results...</em></p>');
				},
				"json"
			);
		} else $('div#searchresults').remove();
	});

	if ( $('input[name=searchterm]').val().length > 0 ) $('input[name=searchterm]').keyup();
	
});


$.fn.timesheetHover = function() {
	$(this).hoverIntent( function() {
	
		$(this).removeClass('dismiss');
	
	}, function() {
	
		$(this).addClass('dismiss');
	
	});
}

$.fn.linkReplace = function() {
	
	$(this).each( function(i) {
		$(this).replaceWith('<a href="#" name="'+$(this).attr('name')+'" class="'+$(this).attr('class')+'">'+$(this).attr('value')+'</a>');
	});
	
	$('a.linkReplace').click( function (e) {
		e.preventDefault();
		
		if ( $(this).attr('name').trim() == 'submit' ) $(this).attr('name', 'submitval');
		
		$(this).after('<input type="hidden" name="'+$(this).attr('name')+'" value="'+$(this).text()+'" />');
		
		$(this).parents('form').submit();
	});
}

$.fn.fieldsetTabs = function ( ) {
	var legends = new Array();
	var html = '<ul id="panelmenu" class="clearfix">';
	var fieldsets = $(this).find('fieldset');
	
	//hide save button
	if (fieldsets.length > 1) {
	
		//get all legends.
		for (i = 0; i < fieldsets.length; i++) {
			legends[i] = $(fieldsets[i]).find('legend').text();
			$(fieldsets[i]).find('legend').remove();
		}
		
		//hide first, set up links and buttons
		for (i = 0; i < fieldsets.length; i++) {
			$(fieldsets[i]).attr("id", "panel_" + i);
			
			if ( i > 0 ) {
				$(fieldsets[i]).hide();
				html += '<li><a href=\"javascript:void(0);\" id="panellink_'+ i +'" class="panellink">' + legends[i] + '</a></li>';
			} else html += '<li class="selected"><a href=\"javascript:void(0);\" id="panellink_'+ i +'" class="panellink">' + legends[i] + '</a></li>';
			
		}
		
		html += '</ul>';
		
		$(this).prepend(html);
		
		$('.panellink').click(function() {
			pieces = $(this).attr('id').split('_');
			
			for (i = 0; i < fieldsets.length; i++) {
				if ( i == pieces[1] ) {
					$(fieldsets[i]).show();
					
					if ( i == fieldsets.length - 1 ) $('.savebutton').show();
					else $('.savebutton').hide();
					
					$('#panellink_'+i).parent().addClass('selected');
					
				} else {
					$(fieldsets[i]).hide();
					$('#panellink_'+i).parent().removeClass('selected');	
				}
			}
			return false;
		});
	}
	
	return this;
}

$.fn.hideMeShow = function(target) {
	this.click(function(e) {
		e.preventDefault();
		$(target).slideToggle('normal', function() {
			if ( $(target).is(':visible') ) {
				$(this).addClass('close');
				$(this).removeClass('open');
			} else {
				$(this).addClass('open');
				$(this).removeClass('close');
			}
		});
	});
}

$.fn.addOptionTo = function(targetSelect, getValueFrom, contentType, fieldName, container) {
	this.click(function(e) {
		newValue = $(getValueFrom).val();
		
		if (newValue.length) {
			$.ajax({
					type: "POST",
					url: siteURL + "/admin/addField_ajax/",
					data: "value="+newValue+"&contenttype="+contentType+"&field="+fieldName,
					success: function(newId) {
						$("<option value=\""+newId+"\">"+ newValue + "</li>").appendTo(targetSelect);
						
						$(getValueFrom).val("");
						$(targetSelect).show();
						$(container).hide();
					}
				});
		}
		return false;
	});
	
}

$.fn.markAs = function (marktype) {
	this.click( function (e) {
		e.preventDefault();
		e.stopPropagation();
		
		var target = $(this).parents('li');
		var link = $(this);
		
		if (target.length == 0) {
			target = $(this).parents('div');
		}
		
		var targetString = target.attr('id');
		var targetArray = new Array();
				
		if ( $(this).hasClass('all') ) {
			target = $('li.date-wgo-' + $(this).attr('title') ) ;
			
			target.each( function(i) {
				targetArray.push( $(this).attr('id') );
			} );
		}
	
		$.post( siteURL + '/epicentr/markAs',
			{marktype: marktype,
			object: targetString,
			'objectArray[]': targetArray },
			function (completed) {
				$(target).addClass(marktype);
				
				if ( link.hasClass('all') ) {
					if (marktype == 'dismiss') {
						$(target).each( function () {
							$(this).find('a.dismiss').each( function() {
								$(this).text('Recall');
								$(this).unbind('click');
								$(this).markAs('recall');
								$(this).removeClass('dismiss');
								$(this).addClass('recall');	
							});
							
							$(target).removeClass('recall');
							$(target).timesheetHover();	
							
						} );
					}
				
				} else {
				
					if (marktype == 'complete') {
						$(link).text('Set as Not Complete');
						$(link).unbind('click');
						$(link).markAs('notcomplete');
						$(link).removeClass('complete');
						$(link).addClass('notcomplete');
						$(target).removeClass('notcomplete');
					}
					
					if (marktype == 'notcomplete') {
						$(link).text('Set as Complete');
						$(link).unbind('click');
						$(link).markAs('complete');
						$(link).removeClass('notcomplete');
						$(link).addClass('complete');
						$(target).removeClass('complete');
					}
					
					if (marktype == 'dismiss') {
						$(link).text('Recall');
						$(link).unbind('click');
						$(link).markAs('recall');
						$(link).removeClass('dismiss');
						$(link).addClass('recall');
						$(target).removeClass('recall');
						$(target).timesheetHover();
					}
					
					if (marktype == 'recall') {
						$(link).text('Dismiss');
						$(link).unbind('click');
						$(link).markAs('dismiss');
						$(link).removeClass('recall');
						$(link).addClass('dismiss');
						$(target).removeClass('dismiss');
						$(target).unbind('mouseover').unbind('mouseout');
					}
					
				}			
			}
		);
	
	});
}

$.fn.showIfChecked = function (showMe) {
	//first set depending on form status on return
	if ($(this).attr('checked') ) $(showMe).show();
	else $(showMe).hide();
	
	this.click( function () {
		if ($(this).attr('checked') ) $(showMe).show();
		else $(showMe).hide();
	});

}

$.fn.rowToggle = function () {
	var toggler = this.find('td a.opener');
	
	toggler.click( function() {
		var parentid = $(this).parent().parent().attr('id');
		var currenttext = $(this).text();
		
		$('#'+parentid+'_data').toggle();
		
		if (currenttext == "+") $(this).html('-');
		if (currenttext == "-") $(this).html('+');
		
		return false;
	});
}

$.fn.addCostCenter = function () {
	this.click( function () {
		var parentTable = $(this).parent().parent().parent().find('table');
		var parentTableId = parentTable.attr('id');
		
		var jobidField = $('#jobid');

		//get data from appropriate fields
		var costcenterField = $('#costcenter');
		var startdateField = $('#start_date');
		var enddateField = $('#end_date');
		var hoursField = $('#allocatedhours');
		
		
		
		//check for values in appropriate fields
		if (!costcenterField.val().length) {
			console.log('no cc');
		} else {
			//send via ajax. to server
			$.ajax({
					type: "POST",
					url: siteURL + "/jobs/addCostCenter_ajax/",
					data: {	jobid : jobidField.val(),
							costcenterid : costcenterField.val(),
							startdate : startdateField.val(),
							enddate : enddateField.val(),
							allocatedhours : hoursField.val() },
					success: function(newId) {
						$('<tr id="cc'+newId+'"><td>'+costcenterField.children(':selected').text()+'</td><td>'+startdateField.val()+'</td><td>'+enddateField.val()+'</td><td>'+hoursField.val()+'</td><td class="edit_textinput" id="'+costcenterField.val()+'|job_costcenter|completion">0</td><td><a href="'+siteURL+'/users/showAssignedUsers/'+jobidField.val()+'/'+costcenterField.val()+'?height=300&width=600&modal=true" title="Assign Users To '+costcenterField.children(':selected').text()+'" class="thickbox">User Assignment</a><br /><a href="'+siteURL+'/jobs/showUpdates/companyid/'+jobidField.val()+'/'+costcenterField.val()+'?TB_iframe=true&height=500&width=600" title="View Updates For '+costcenterField.children(':selected').text()+'" class="thickbox">View Updates</a></td></tr>').appendTo('#'+parentTableId+' tbody');
						
						//$('#cc'+newId+' .deleteCostcenter').deleteCostcenter();
						startdateField.val('');
						enddateField.val('');
						hoursField.val('');
						
						$('#activity_costcenter').append('<option value="'+newId+'">'+costcenterField.children(':selected').text()+'</option>');
						
						parentTable.find('thead').css('display', 'table-header');
						parentTable.find('thead tr').css('display', 'table-row');
						parentTable.parent().find('p.whynot').fadeOut();
						
						if (!$('#activityform').is(':visible')) {
							$('#activityform').show();
							$('#activityform').parent().find('.extra').hide();
						}
						
					}
				});
		}
	});
}




$.fn.addActivity = function () {
	var jobId = $('#jobid').val();
	var companyId = $('#companyid').val();

	this.click( function () {
		//get id of parent table
		var parentTable = $(this).parent().parent().parent().find('table');
		var parentTableId = parentTable.attr('id');

		
		//get data from appropriate fields
		var ccField = $('#activity_costcenter');
		var titleField = $('#activity_title');
		var startdateField = $('#activity_startdate');
		var enddateField = $('#activity_enddate');
		var allocatedHoursField = $('#activity_allocatedhours');
		var notesField = $('#activity_notes');
		
		if ( $('#isdeadline:checked').length ) isdeadline = true;
		else  isdeadline = false;
		
		if ( $('#ismilestone:checked').length ) ismilestone = true;
		else ismilestone = false;
		
		//check for values in appropriate fields
		if (!titleField.val().length) {
			$('<span class="error">Please give this task a title</span>').insertAfter(titleField);
		} else if ( !enddateField.val().length && (isdeadline || ismilestone) ) {
			$('<span class="error">Please supply a Due Date for this task.</span>').insertAfter(enddateField);
		} else {
			//send via ajax. to server
			$.ajax({
					type: "POST",
					url: siteURL + "/jobs/addActivity_ajax/",
					data: { jobid: jobId,
							companyid: companyId,
							job_centerid : ccField.val(),
							activity_title : titleField.val(),
							startdate : startdateField.val(),
							enddate : enddateField.val(),
							allocatedhours : allocatedHoursField.val(),
							activity_notes : notesField.val(),
							isdeadline: isdeadline,
							ismilestone: ismilestone},
					success: function(newId) {
						$('<tr><td>'+ccField.children(':selected').text()+'</td><td>'+titleField.val()+'</td><td>'+startdateField.val()+'</td><td>'+enddateField.val()+'</td><td>'+allocatedHoursField.val()+'</td><td>'+notesField.val()+'</td><td><button class="deleteActivity">Delete</button></td></tr>').appendTo('#'+parentTableId+' tbody');
					
						//$('#activity'+groupid+'-'+newId+' .deleteActivity').deleteActivity();
						titleField.val('');
						startdateField.val('');
						enddateField.val('');
						allocatedHoursField.val('');
						notesField.val('');
						
						parentTable.find('thead').css('display', 'table-header');
						parentTable.find('thead tr').css('display', 'table-row');
						parentTable.parent().find('p.whynot').fadeOut();
					}
				});
		}
	});
}

$.fn.addCost = function () {
	this.click( function () {
		var parentTable = $(this).parent().parent().parent().find('table');
		var parentTableId = parentTable.attr('id');
		
		var jobidField = $('#jobid');

		//get data from appropriate fields
		var titleField = $('#cost_title');
		var quoteField = $('#quote_ref');
		var supplierField = $('#supplierid');
		var incostField = $('#incoming_cost');
		var outcostField = $('#outgoing_cost');
		var descriptionField = $('#cost_description');
		
		//check for values in appropriate fields
		if (!titleField.val().length) {
			console.log('no title');
		} else {
			//send via ajax. to server
			$.ajax({
					type: "POST",
					url: siteURL + "/jobs/addCost_ajax/",
					data: {	jobid : jobidField.val(),
							cost_title : titleField.val(),
							quote_ref : quoteField.val(),
							supplierid : supplierField.val(),
							incoming_cost : incostField.val(),
							outgoing_cost : outcostField.val(),
							cost_description : descriptionField.val() },
					success: function(newId) {
						$('<tr><td>'+titleField.val()+'</td><td>'+quoteField.val()+'</td><td>'+supplierField.children(':selected').text()+'</td><td>'+incostField.val()+'</td><td>'+outcostField.val()+'</td><td>'+descriptionField.val()+'</td><td><button class="deleteCost">Delete</button></td></tr>').appendTo('#'+parentTableId+' tbody');
						
						
						//$('#cc'+newId+' .deleteCostcenter').deleteCostcenter();
						titleField.val('');
						quoteField.val('');
						incostField.val('');
						outcostField.val('');
						descriptionField.val('');
						
						parentTable.find('thead').css('display', 'table-header');
						parentTable.find('thead tr').css('display', 'table-row');
						parentTable.parent().find('p.whynot').fadeOut();
					}
				});
		}
	});
}

$.fn.selectAdd = function() {
	if (!this.length) return false;
	
	var fieldid = $(this).attr('id');
	var fieldbits = fieldid.split('_');
	
	var model = fieldbits[0];
	var targetinput = fieldbits[1];
	var addfield = fieldbits[2];
	
	var addLink = $(this);
	
	$(this).click(function (e) {
		$("#"+fieldid+"_container").toggle();
		$(this).toggle();
		return false;
	});
	
	$("#"+fieldid+"_container").children('a.cancel').click( function(e) {
		e.preventDefault();
		
		$(this).parent().hide();
		
		$(addLink).show();
	});
	
	$("#"+fieldid+"_button").click(function (e) {
		var fieldvalue = $("#"+fieldid+"_field").attr('value');
		
		if (fieldvalue != undefined) {
			$.ajax({
					type: "POST",
					url: siteURL + "/admin/addField_ajax/",
					data: "value="+fieldvalue+"&contenttype="+model+"&field="+addfield,
					success: function(newId) {
						$("<option value=\""+newId+"\">"+ fieldvalue + "</li>").appendTo('#'+targetinput);
						
						$("#"+fieldid+"_field").val("");
						$('#'+targetinput).show();
						$("#"+fieldid+"_container").toggle();
						addLink.show();
					}
				});
		}
		
		return false;
	});
	
}